package com.masu.knows.faq.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.masu.knows.commons.exception.ServiceException;
import com.masu.knows.commons.model.*;
import com.masu.knows.faq.dto.QuestionDTO;
import com.masu.knows.faq.mapper.*;
import com.masu.knows.faq.service.IQuestionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 沈传尚
 * @since 2021-12-07
 */
@Service
@Slf4j
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements IQuestionService {
    @Autowired
    private TagServiceImpl tagService;

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private QuestionTagMapper tagMapper;

    @Autowired
    private UserQuestionMapper userQuestionMapper;

    @Resource
    private AnswerMapper answerMapper;

    @Resource
    private CommentMapper commentMapper;


    @Override
    public PageInfo<Question> getMyQuestions(String username, Integer pageNum, Integer pageSize) {
        // 获取当前登录的用户
        User user = getUser(username);
        // 查询该用户的所有问题
        QueryWrapper<Question> wrapper=new QueryWrapper<>();
        wrapper.lambda().eq(Question::getUserId,user.getId())
                .eq(Question::getStatus,0).orderByDesc(Question::getCreatetime);
        PageHelper.startPage(pageNum,pageSize);
        List<Question> questions = questionMapper.selectList(wrapper);
        for (Question question : questions){
            question.setTags(tagNames2Tag(question.getTagNames()));
        }
        return new PageInfo<>(questions);
    }

    @Override
    public PageInfo<Question> getTeacherQuestions(String username, Integer pageNum, Integer pageSize) {
        // 获取当前的登录的讲师
        User user = getUser(username);
        // 分页查询数据(必须在查询之前设置 否则pageSize不生效)
        PageHelper.startPage(pageNum,pageSize);
        // 查询出当前讲师的提出的问题 以及需要回答的问题
        List<Question> questions = questionMapper.findAllTeachersQuestion(user.getId());

        for (Question question : questions){
            question.setTags(tagNames2Tag(question.getTagNames()));
        }
        return new PageInfo<>(questions);
    }

    @Override
    @Transactional
    public  void   saveQuestion(QuestionDTO questionDTO, String username) {
        // 1. 根据用户名获取用户信息
        User user = getUser(username);
        // 2. 处理标签
        StringBuilder builder=new StringBuilder();
        for (String tagName : questionDTO.getTagNames()){
            builder.append(tagName).append(",");
        }
        String tagNames = builder.deleteCharAt(builder.length() - 1).toString();
        // 3. 向数据表插入问题对象
        Question question=new Question();
        question.setTitle(questionDTO.getTitle())
                .setContent(questionDTO.getContent())
                .setUserNickName(user.getNickname())
                .setUserId(user.getId())
                .setStatus(0)
                .setPageViews(0)
                .setPublicStatus(0)
                .setDeleteStatus(0)
                .setTagNames(tagNames);
        int row = questionMapper.insert(question);
        if (row != 1){
            throw new ServiceException("新增数据异常");
        }

        // 4.新增问题id和标签id的对应关系到数据表
        Map<String, Tag> tagMaps = tagService.tagsMap();
        for (String tag : questionDTO.getTagNames()){
            Integer tagId = tagMaps.get(tag).getId();
            QuestionTag questionTag=new QuestionTag();
            questionTag.setQuestionId(question.getId());
            questionTag.setTagId(tagId);
            int r = tagMapper.insert(questionTag);
            if (r != 1){
                throw new ServiceException("新增数据异常");
            }
            log.debug("新增了问题与标签之间的关系:{}", questionTag);
        }

        // 5.新增问题和老师之间的关系
        String url="http://sys-service/v1/users/master";
        User[] users=restTemplate.getForObject(url,User[].class);
        //实例化讲师集合
        Map<String,User> teacherMap=new HashMap<>();
        //编辑所有讲师数组,为map赋值
        if (users != null ){
            for(User u:users){
                teacherMap.put(u.getNickname(),u);
            }
        }
        for (String s : questionDTO.getTeacherNicknames()){
            UserQuestion userQuestion=new UserQuestion();
            userQuestion.setUserId(teacherMap.get(s).getId());
            userQuestion.setQuestionId(question.getId());
            int r1 = userQuestionMapper.insert(userQuestion);
            if (r1 != 1){
                throw new ServiceException("新增数据异常");
            }
            log.debug("新增了问题与老师之间的关系:{}", userQuestion);
        }
    }

    @Override
    public Question findQuestionById(Integer id) {
        Question question = questionMapper.selectById(id);
        List<Tag> tagList = tagNames2Tag(question.getTagNames());
        question.setTags(tagList);
        return question;
    }

    @Override
    @Transactional
    public void deleteQuestion(Integer qid) {
        // 判断该问题有没有回答
        List<Answer> answers = answerMapper.selectList(new QueryWrapper<Answer>().lambda().eq(Answer::getQuestId, qid));
        if (answers.size()>0){
            //判断该问题有无评论
            List<Integer> answerIds = answers.stream().map(Answer::getId).collect(Collectors.toList());
            List<Comment> comments = commentMapper.selectList(new QueryWrapper<Comment>().lambda().in(Comment::getAnswerId, answerIds));
            if (comments.size()>0){
                // 删除评论
                List<Integer> commentIds = comments.stream().map(Comment::getId).collect(Collectors.toList());
                commentMapper.deleteBatchIds(commentIds);
            }

            // 删除回答
            answerMapper.deleteBatchIds(answerIds);
        }

        // 删除问题与标签的对应关系
        tagMapper.delete(new QueryWrapper<QuestionTag>().lambda().eq(QuestionTag::getQuestionId,qid));

        // 删除用户与问题的对应关系
        userQuestionMapper.delete(new QueryWrapper<UserQuestion>().lambda().eq(UserQuestion::getQuestionId,qid));

        // 删除问题
        questionMapper.deleteById(qid);

    }

    /**
     * 将tag标签名转为tag对象
     * @param tags
     * @return
     */
    private List<Tag> tagNames2Tag(String tags){
        // java基础,javaSE,java
        String[] split = tags.split(",");
        Map<String, Tag> tagMap = tagService.tagsMap();
        List<Tag> tagList=new ArrayList<>();
        for (String s : split){
            tagList.add(tagMap.get(s));
        }
       return tagList;
    }


    @Autowired
    private RestTemplate restTemplate;
    public User getUser(String username){
        String url="http://sys-service/v1/auth/user?username={1}";
        return restTemplate.getForObject(url,User.class,username);
    }

}
